package mystack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 224 基本计算器
 *  输入 s="(1+(4+5+2)-3+(6+8)"
 *  输出 23
 */
public class Calc {

    public int calculate(String s) {
        Deque<Integer> ops = new LinkedList<Integer>();
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;
        while (i < n) {
            char at = s.charAt(i);
            if (at == ' ') {
                i++;
            } else if (at == '+') {
                sign = ops.peek();
                i++;
            } else if (at == '-') {
                sign = -ops.peek();
                i++;
            } else if (at == '(') {
                ops.push(sign);
                i++;
            } else if (at == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + at - '0';
                    i++;
                }
                ret += sign * num;
            }
        }
        return ret;
    }



    public long parse(String s){
        int length = s.length();
        long num=0;
        for (int i = 0; i <length ; i++) {
            int h=s.charAt(i)-'0';
            num=num*10+h;
        }
        return num;
    }

    public static void main(String[] args) {
        Calc calc = new Calc();
//        long parse = calc.parse("1234");
//        System.out.println(parse);
        int calculate = calc.calculate("(1+(4+5+2)-3+(6+8)");
        System.out.println(calculate);
    }
}
